package com.imooc.reader.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.imooc.reader.enity.*;
import com.imooc.reader.service.BookService;
import com.imooc.reader.service.CategoryService;
import com.imooc.reader.service.EvaluationService;
import com.imooc.reader.service.MemberService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class BookController {
    @Resource
    CategoryService categoryService;

    @Resource
    BookService bookService;

    @Resource
    EvaluationService evaluationService;

    @Resource
    private MemberService memberService;

    /**
     * 显示分布列表
     * @return
     */
    @GetMapping("/")
    public ModelAndView showIndex(){
        ModelAndView modelAndView = new ModelAndView("/index");
        List<Category> list = categoryService.selectAll();
        modelAndView.addObject("categoryList",list);
        return  modelAndView;
    }

    /**
     * 分页查看书
     * @param p
     * @return
     */
    @GetMapping("/books")
    @ResponseBody
    public IPage<Book> selectBook(Long categoryId,String order, Integer p){
        if (p==null){
            p=1;
        }
        IPage<Book> paging = bookService.paging(categoryId,order,p, 10);
        return paging;
    }

    /**
     * 图书详情
     * @param bookId
     * @return
     */
    @GetMapping("/book/{bookId}")
    @ResponseBody
    public ModelAndView selectBook(@PathVariable("bookId") Long bookId, HttpSession session){
        ModelAndView modelAndView = new ModelAndView("detail");
        Book book = bookService.selectById(bookId);
        List<Evaluation> evaluations = evaluationService.selectByBookId(bookId);
        modelAndView.addObject("book",book);
        modelAndView.addObject("evaluationList",evaluations);
        Member member = (Member)session.getAttribute("loginMember");
        // 获取会员阅读状态
        if (member!=null){
            MemberReadState memberReadState = memberService.selectMemberReadState(member.getMemberId(), bookId);
            modelAndView.addObject("memberReadState",memberReadState);
        }
        return modelAndView;
    }

}
